package wei.zhang.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

/**
 * 分表策略；
 *      复杂策略
 */
public class ComplexTableShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargeNames, ComplexKeysShardingValue<Long> complexKeysShardingValue) {

        Map<String, Range<Long>> columnNameAndRangeValuesMap = complexKeysShardingValue.getColumnNameAndRangeValuesMap();
        Range<Long> id = columnNameAndRangeValuesMap.get("id");
        Collection<Long> cid = complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("cid");

        ArrayList<String> objects = new ArrayList<>();

        for (Long cId :cid) {
            BigInteger bigInteger = BigInteger.valueOf(cId);
            BigInteger addResult = (bigInteger.mod(new BigInteger("2"))).add(new BigInteger("1"));
            objects.add(complexKeysShardingValue.getLogicTableName()+"_"+addResult);
        }

        return objects;
    }
}
